#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>//close
#include"Log.hpp"

#define BACKLOG 5

class TcpServer
{
private:
    int port;
    int listen_sock;
    static TcpServer *svr;

private:
    TcpServer(int _port) : port(_port), listen_sock(-1)
    {
    }
    TcpServer(const TcpServer &ts) = delete;
    TcpServer &operator=(const TcpServer ts) = delete;

public:
    static TcpServer *GetInstance(int _port) //获取单例
    {
        static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
        if (nullptr == svr) //为空就申请，不为空就直接返回
        {
            pthread_mutex_lock(&mtx);
            if (nullptr == svr)
            {
                svr = new TcpServer(_port);
                svr->Socket();
                svr->Bind();
                svr->Listen();
            }
            pthread_mutex_unlock(&mtx);
        }
        return svr;
    }
    void InitServer()
    {
        Socket();
        Bind();
        Listen();
    }
    void Socket()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock < 0)
        {
            LOG(FATAL, "socket error");
            exit(1);
        }
        LOG(INFO, "create socket ... success");
        //保证服务挂掉之后能够立即重启（防止bind error）
        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); //
    }
    void Bind()
    {
        struct sockaddr_in local; //
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY; //
        if (bind(listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error");
            exit(2);
        }
        LOG(INFO, "bind socket ... success");
    }
    void Listen()
    {
        if (listen(listen_sock, BACKLOG) < 0)
        {
            LOG(FATAL, "listen error");
            exit(3);
        }
        LOG(INFO, "listen socket ... success");
    }
    int Sock()
    {
        return listen_sock;
    }
    ~TcpServer() 
    {
        if(listen_sock >= 0)
            close(listen_sock);
    }
};
TcpServer *TcpServer::svr = nullptr;
